package cn.stylefeng.guns.modular.business.frequency.orderfinishrecord.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.page.AndaPageResult;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.modular.business.frequency.orderfinish.model.param.FinishRecordDTO;
import cn.stylefeng.guns.modular.business.frequency.orderfinish.model.param.OrderFinishRecordVO;
import cn.stylefeng.guns.modular.business.frequency.orderfinishrecord.service.OrderFinishRecordService;
import cn.stylefeng.guns.modular.business.frequency.orderlogistics.model.param.ErrorMsg;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.param.OrderDTO;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.PkgOrderFinishRecord;
import cn.stylefeng.guns.modular.business.frequency.ordersub.model.result.PkgTake;
import cn.stylefeng.guns.modular.business.frequency.ordertake.mapper.OrderTakeMapper;
import cn.stylefeng.guns.modular.business.frequency.ordertake.service.OrderTakeService;
import cn.stylefeng.guns.modular.business.frequency.statistics.PkgOrderFinish;
import cn.stylefeng.guns.modular.business.util.BusinessUtil;
import cn.stylefeng.guns.sys.modular.user.mapper.SysUserMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单交付记录表 控制器
 *
 * @author: yujie
 * @date: 2023/05/09 17:16
 */
@RestController
@RequestMapping("/api/finish")
public class OrderFinishRecordController {

    @Resource
    private OrderFinishRecordService finishService;
    @Resource
    private SysUserMapper userMapper;
    @Autowired
    private OrderTakeMapper orderTakeMapper;

    @ApiOperation(value = "待交付订单分页列表")
    @GetMapping("/wait")
    public ResponseData getWaitFinishListPage(OrderDTO orderDTO) {
        //orderDTO.setStatusOnly(OrderStatusEnum.WAIT_TAKE.status);
        getFinishWaitQueryParam(orderDTO);
        //page.setOptimizeCountSql(false);
        //if (page.getOrders().size() == 0) {
        //    page.addOrder(OrderItem.desc("orderId"));
        //}
        //page.setOptimizeCountSql(false);
        //
        if (ObjectUtil.isNull(orderDTO.getColumn())) {
            orderDTO.setColumn("orderId");
        }

        Page list = finishService.getWaitFinishListPage(PageFactory.defaultPage(), orderDTO);
        return ResponseData.andaSuccess(new AndaPageResult<>().AndaPageResult(list, orderDTO));
    }

    //@Log("订单批量交付交付")
    @ApiOperation(value = "交付")
    @PostMapping
    public ResponseData finish(@RequestBody OrderFinishRecordVO orderFinishRecordVO) {
        ErrorMsg errorMsg = new ErrorMsg();
        if (!finishService.checkFinishAdd(orderFinishRecordVO, errorMsg)) {
            return ResponseData.andaError(errorMsg.getErrorMsg());
        }
        Long userId = LoginContextHolder.me().getSysLoginUserId();
        finishService.finish(userId, orderFinishRecordVO, null);
        return ResponseData.andaSuccess();
    }

    @ApiOperation(value = "交付回退")
    @GetMapping("/reDelivery/{orderId}")
    public ResponseData reDelivery(@PathVariable Long orderId) {
        finishService.reFinish(orderId);
        return ResponseData.andaSuccess();
    }

    //@Log("直交客户确认到达")
    @ApiOperation("直交客户确认到达")
    @PostMapping("/level")
    public ResponseData levelFinish(@RequestBody OrderFinishRecordVO orderFinishRecordVO) {
        ErrorMsg errorMsg = new ErrorMsg();
        if (!finishService.checkLevelFinish(orderFinishRecordVO, errorMsg)) {
            return ResponseData.andaError(errorMsg.getErrorMsg());
        }
        finishService.levelFinish(orderFinishRecordVO);
        return ResponseData.andaSuccess();
    }

    //@Log("直交客户确认到达")
    @ApiOperation("直交客户确认到达回退")
    @PostMapping("/reLevel/{orderId}")
    public ResponseData reLevelFinish(@PathVariable Long orderId) {

        finishService.reLevelFinish(orderId);
        return ResponseData.andaSuccess();
    }

    @Autowired
    private OrderTakeService orderTakeService;

    @ApiOperation(value = "已完成交付分页列表")
    @GetMapping("/record")
    public ResponseData getOrderFinishListPage(FinishRecordDTO orderDTO) {
        if (ObjectUtil.isNull(orderDTO.getColumn())) {
            orderDTO.setColumn("ofr.create_time");
        }
        getFinishOverQueryParam(orderDTO);
        Page<PkgOrderFinish> list = finishService.getFinishOverListPage(PageFactory.defaultPage(), orderDTO);

        List<Long> orderIdList = list.getRecords().stream().map(x -> x.getOrderId()).collect(Collectors.toList());
        Map<Long, PkgTake> pkgTakeMap = orderTakeService.getPkgTakeMap(orderIdList);
        for (PkgOrderFinish delivery : list.getRecords()) {
            if (pkgTakeMap.get(delivery.getOrderId()) != null) {
                delivery.setTakeCarFee(pkgTakeMap.get(delivery.getOrderId()).getTakeCarFee());
            }
        }

        return ResponseData.andaSuccess(new AndaPageResult<>().AndaPageResult(list, orderDTO));
    }

    @ApiOperation(value = "已完成交付详情")
    @GetMapping("/over/{id}")
    public ResponseData getFinishOverDetail(@PathVariable String id) {
        PkgOrderFinishRecord orderFinishRecord = finishService.getPkgOrderFinishRecordDetail(id);
        return ResponseData.andaSuccess(orderFinishRecord);
    }

    @ApiOperation(value = "订单转账凭证")
    @GetMapping("/{orderId}/transfer-voucher")
    public ResponseData getOrderFinishPayImage(@PathVariable String orderId) {
        List<String> list = finishService.getOrderFinishPayImage(orderId);
        return ResponseData.andaSuccess(list);
    }

    private void getFinishOverQueryParam(FinishRecordDTO orderDTO) {
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        orderDTO.setDataList(empByOrgList);
    }


    @Resource
    private BusinessUtil businessUtil;

    private void getFinishWaitQueryParam(OrderDTO orderDTO) {
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        orderDTO.setDataList(empByOrgList);
        orderDTO.setSiteId(businessUtil.getSiteId());


    }

}
